﻿using System;
using UnityEngine;

public class MaxLocationSize : NodeSize
{
    public RectTransform rectTransform;
    public float maxWidth;
    public float maxHeight;
    public float maxWidthRatio;
    public float maxHeightRatio;
    public Vector3 position;
    public Vector3 maxPosition;
    public bool anchor;
    public MaxAnchorsItem anchors;
    public MaxAnchorsItem maxAnchors;

    protected override void OnRefresh(float rw, float rh, float w, float h, float s)
    {
        SetValue(w / h, w, h);
    }

    private void SetValue(float ratio, float width, float height)
    {
        if (maxWidthRatio > 0 || maxWidth > 0)
        {
            bool isMaxWidth = IsMaxWidth(ratio, width);
            if (anchor)
            {
                rectTransform.anchorMax = isMaxWidth ? maxAnchors.max : anchors.max;
                rectTransform.anchorMin = isMaxWidth ? maxAnchors.min : anchors.min;
                rectTransform.pivot = isMaxWidth ? maxAnchors.pivot : anchors.pivot;
                rectTransform.anchoredPosition = isMaxWidth ? maxPosition : position;
            }
            else
            {
                rectTransform.localPosition = isMaxWidth ? maxPosition : position;
            }
        }
        else if (maxHeightRatio > 0 || maxHeight > 0)
        {
            bool isMaxHeight = IsMaxHeight(ratio, height);
            if (anchor)
            {
                rectTransform.anchorMax = isMaxHeight ? maxAnchors.max : anchors.max;
                rectTransform.anchorMin = isMaxHeight ? maxAnchors.min : anchors.min;
                rectTransform.pivot = isMaxHeight ? maxAnchors.pivot : anchors.pivot;
                rectTransform.anchoredPosition = isMaxHeight ? maxPosition : position;
            }
            else
            {
                rectTransform.localPosition = isMaxHeight ? position : maxPosition;
            }
        }
    }

    bool IsMaxWidth(float ratio, float width)
    {
        if (maxWidthRatio > 0) return ratio > maxWidthRatio;
        if (maxWidth > 0) return width > maxWidth;
        return false;
    }

    bool IsMaxHeight(float ratio, float height)
    {
        if (maxHeightRatio > 0) return ratio > maxHeightRatio;
        if (maxHeight > 0) return height > maxHeight;
        return false;
    }

    [Serializable]
    public class MaxAnchorsItem
    {
        public Vector2 max = new(0.5f, 0.5f);
        public Vector2 min = new(0.5f, 0.5f);
        public Vector2 pivot = new(0.5f, 0.5f);
    }
}